package com.lxb.blog.service.ImpI;

import com.lxb.blog.NotFoundException;
import com.lxb.blog.dao.TypeRepository;
import com.lxb.blog.entity.Type;
import com.lxb.blog.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TypeServiceImpI  implements TypeService{

    @Autowired
    private TypeRepository typeRepository;

    //保存（新增）
    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    //通过id获得某个type
    @Transactional
    @Override
    public Type getType(Integer id) {
        return typeRepository.getOne(id);
    }

    //分页(获得type列表)
    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    //更新
    @Transactional
    @Override
    public Type updateType(Integer id, Type type) {
        Type t = typeRepository.getOne(id);
        if(t == null){
            throw   new NotFoundException("不存在该字符集");
        }
        //把type对象复制给t对象
        BeanUtils.copyProperties(type,t);
        return typeRepository.save(t);
    }

    //删除
    @Transactional
    @Override
    public void deleteType(Integer id) {

        typeRepository.deleteById(id);
    }

    @Override
    public Type getTypeByname(String name) {

        return typeRepository.findByName(name);
    }

    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return typeRepository.findTopBy(pageable);
    }
}
